<template>
	<view class="full-width">
		<view class="input row module-picker-input" :style="{focused: isInputFocused}">
			<text class="text" @click="handleOpenPopup">{{content}}</text>
			<uni-icons v-show="isShowClearButton" type="clear" size="25" color="#c0c4cc" @click="handleResetClick"></uni-icons>
		</view>
		<uni-popup 
			ref="popup" 
			:safe-area="false"
			backgroundColor="#fff"
			border-radius="10px 10px 0 0"
			@maskClick="handlePopupClose">
			<uni-nav-bar 
				v-if="loaded" 
				:title="$t('module.select-module-name')" 
				:border="false" 
				right-icon="closeempty"
				@clickRight="handleClosePopup"></uni-nav-bar>
			<uni-segmented-control
				v-if="loaded" 
				class="left-align module-tab" 
				:current="tabActionIndex" 
				:values="tabs" 
				style-type="text"
				:active-color="tabActiveColor" 
				@clickItem="handeTabClick" />
			<uni-list>
				<uni-list-item 
					:title="m.moduleName" 
					v-for="m in currentModuleList" 
					:key="m.moduleId"
					clickable
					@click="handleModuleClick(m)">
					<template v-slot:footer>
						<uni-icons v-if="isSelect(m)" type="checkmarkempty" color="#2979ff" size="18"></uni-icons>
					</template>
				</uni-list-item>
			</uni-list>
			<view class="bottom"></view>
		</uni-popup>
	</view>
</template>

<script>
	import config from '@/config'
	import {listModule, treeModule} from "@/api/system/module";
	
	export default {
		name: 'ModulePicker',
		model: {
			type: 'value',
			event: 'input'
		},
		data() {
			return {
				isInputFocused: false,
				tabActiveColor: '#007aff',
				tabActionIndex: 0,
				// 标签显示的从父到子交付物集合
				tabModuleList: [],
				// 当前页的交付物集合
				currentModuleList: [],
				moduleTree: [],
				modulePropertyMap: {
					value: 'moduleId',
					text: 'moduleName'
				}
			}
		},
		props: {
			value: {
				type: Number,
				default: 0,
			},
		},
		watch: {
			value: function(v) {
				this._reset();
				this.getModuleTree(v);
			}
		},
		computed: {
			/** 是否加载完成  */
			loaded() {
				return this.$i18n.locale?true:false;
			},
			/** 是否显示清空按钮  */
			isShowClearButton() {
				return this.tabModuleList.length>0;
			},
			/** 当前项目名称 */
			projectId() {
			    return this.$store.state.user.config.currentProjectId;
			},
			/** 当前选择的标签数组 */
			tabs: function() {
				const len = this.tabModuleList.length;
				const names = this.tabModuleList.map(m=>m.moduleName);
				// 如果返回的标签为空或者最后一个标签不是叶子节点，就再最后添加一个“请选择标签”
				if(len==0 || this.tabModuleList[len-1].childrenCount>0) {
					return [...names, ...['请选择']];
				} else {
					return names;
				}
			},
			/** 选择显示的内容 */
			content: function() {
				return this.tabModuleList.map(m=>m.moduleName).join(' / ')
			},
			/** 是否是选择的交付物 */
			isSelect: function() {
				return function(module) {
					return this.tabModuleList.filter(m=>m.moduleId===module.moduleId).length>0;
				}
			}
		},
		methods: {
			/** 重设 */
			_reset() {
				this.tabActionIndex = 0;
				this.tabModuleList = [];
				this.currentModuleList = [];
				this.currentModuleList = this.moduleTree;
			},
			/** 重设 */
			reset() {
				this._reset();
				this.$emit('input', 0);
			},
			/** 重设 */
			handleResetClick() {
				this.reset();
			},
			/** 处理打开弹框 */
			handleOpenPopup() {
				this.$refs.popup.open('bottom');
				this.isInputFocused = true;
				this.$emit('open');
			},
			/** 处理关闭弹框 */
			handleClosePopup() {
				this.$refs.popup.close();
				this.handlePopupClose();
			},
			/** 处理关闭弹框事件 */
			handlePopupClose() {
				this.$emit('close');
			},
			/** 处理点击交付物标签 */
			handeTabClick(e) {
				if (this.tabActionIndex !== e.currentIndex) {
					this.tabActionIndex = e.currentIndex;
					// 如果点击的tab索引小于实际tab交付物列表的长度，就更新展示的交付物列表
					if(this.tabActionIndex<this.tabModuleList.length) {
						const module = this.tabModuleList[this.tabActionIndex];
						this.currentModuleList = this.findModuleList(this.moduleTree, module.moduleId);
					}
				}
			},
			/** 处理点击交付物 */
			handleModuleClick(module) {
				// 如果交付物为空就什么也不做
				if(!module) return;
				// 删除多余的tab
				this.tabModuleList = this.tabModuleList.filter((m,i)=>i<this.tabActionIndex);
				this.removeTab(module);
				if(module.childrenCount>0 && module.children.length===0) { 
					// 如果交付物有子节点并且没有获取过子节点，就调接口获取
					this.getModuleList(module.moduleId, module);
				} else if(module.childrenCount === 0) {
					// 如果交付物没有子节点，直接返回选择
					this.addTab(module);
					this.handleClosePopup();
					this.$emit('input', module.moduleId);
				} else if(module.childrenCount === module.children.length) {
					// 如果当前交付物中存在子交付物集合数据
					this.addTab(module);
					this.currentModuleList = module.children;
					this.$emit('input', module.moduleId);
				}
			},
			/** 添加标签 */
			addTab(module) {
				this.tabModuleList.push(module);
				if(module.childrenCount>0) {
					this.tabActionIndex = this.tabModuleList.length;
				} else {
					this.tabActionIndex = this.tabModuleList.length - 1;
				}
			},
			/** 删除标签 */
			removeTab(module) {
				let endIndex = this.tabModuleList.length - 1;
				for(let i=0;i<this.tabModuleList.length;i++) {
					if(module.moduleId===this.tabModuleList[i].moduleId) {
						endIndex = i;
						break;
					}
				}
				this.tabActionIndex = endIndex - 1;
				this.tabModuleList = this.tabModuleList.filter((t,index)=>index<endIndex);
			},
			/** 获取交付物列表 */
			getModuleList(moduleId, node) {
				const query = {
					modulePid: moduleId,
					pageIndex: 1,
					pageSize: 9999,
					projectId: this.projectId
				}
				// 调用获取交付物列表接口
				listModule(query).then(res => {
					const list = res.data;
					if(node) {
						node.children = list;
						this.addTab(node);
					} else {
						this.moduleTree = list;
					}
					this.currentModuleList = list;
				});
			},
			/** 获取交付物树形集合 */
			getModuleTree(moduleId) {
				const query = {
					modulePid: moduleId,
					projectId: this.projectId
				}
				treeModule(query).then(res => {
					this.moduleTree = res.data;
					this.currentModuleList = res.data;
					this.initModuleTree(res.data);
				});
			},
			/** 初始化交付物集合 */
			initModuleTree(nodeList) {
				if(!nodeList) return;
				for(let i=0;i<nodeList.length;i++) {
					const node = nodeList[i];
					if(node.children && node.children.length>0 || node.moduleId===this.value) {
						this.addTab(node);
					}
					if(node.children && node.children.length>0) {
						this.currentModuleList = node.children;
						this.initModuleTree(node.children);
						break;
					}
				}
			},
			/** 在树形交付物结构中根据moduleId查找moduleId所在的交付物列表 */
			findModuleList(moduleTree, findModuleId) {
				if(!findModuleId) {
					return this.moduleTree;
				}
				for(let i=0;i<moduleTree.length;i++) {
					const module = moduleTree[i];
					if(module.moduleId===findModuleId) {
						return moduleTree;
					}
				}
				for(let i=0;i<moduleTree.length;i++) {
					const module = moduleTree[i];
					if(module.childrenCount>0) {
						const ret = this.findModuleList(module.children, findModuleId);
						if(ret && ret.length>0) return ret;
					}
				}
				return [];
			}
		}
	}
</script>

<style lang="scss" scoped>
	.module-picker-input:focus {
		border-color: red;
	}
	::v-deep .module-picker-input {
		.text {
			flex: 1;
			min-height: 50rpx;
			display: inline-flex;
			justify-content: flex-start;
			align-items: center;
		}
		.uni-icons {
			flex-shrink: 0;
		}
	}
	.left-align {
	  margin-right: auto !important;
	  margin-left: 0 !important;
	}
	.bottom {
		width: 100%;
		height: env(safe-area-inset-bottom);
	}
	.module-tab ::v-deep .segmented-control__text {
		color: red;
		font-size: 44px;
	}
	
	::v-deep .segmented-control__item .segmented-control__text > span {
		color: red;
	    white-space: nowrap;        /* 防止文字换行 */
	    overflow: hidden;           /* 隐藏超出部分 */
	    text-overflow: ellipsis;    /* 显示省略号 */
	    position: relative;         /* 为tooltip定位 */
	}
</style>